package com.example.demo.mapper;

import com.example.demo.model.User;
import com.example.demo.model.UserCredit;
import org.apache.ibatis.annotations.*;

@Mapper
public interface UserCreditMapper {
    @Select("SELECT * FROM user_credit WHERE user_id = #{userId}")
    UserCredit findByUserId(@Param("userId") Long userId);

    @Insert("INSERT INTO user_credit (user_id, balance, total_balance) VALUES (#{userId}, #{balance}, #{totalBalance})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertUserCredit(UserCredit userCredit);

    @Insert("INSERT INTO user_credit (user_id) VALUES (#{userId})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void newUserCredit(Long userId);

    @Update("UPDATE user_credit SET balance = #{balance} WHERE user_id = #{userId}")
    void updateBalance(@Param("userId") Long userId, @Param("balance") int balance);

    @Update("UPDATE user_credit SET balance = #{newBalance} " +
            "WHERE user_id = #{userId} AND balance = #{oldBalance}")
    int updateBalanceWithLock(@Param("userId") Long userId,
                              @Param("oldBalance") int oldBalance,
                              @Param("newBalance") int newBalance);
}